/*
The MIT License (MIT)

Copyright (c) 2013 Mike Dapiran, Brian May, Richard Pospesel, and Bert Wierenga

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "hhdConstantBuffer.h"
#include "hhdFactory.h"
#include "tinyxml.h"
#include "hhdMConstantBufferModifier.h"

namespace hhd
{
    ConstantBuffer::ConstantBuffer(void)
		: _shell(16)
    {
        _start_address = NULL;
        _size = 0;
        _shader_bind_flags = SBF_NONE;
    }

    ConstantBuffer::~ConstantBuffer(void)
    {
        if(_start_address)
        {
            Factory::releaseMemoryBlock( _start_address );
        }
    }

    ConstantBuffer::ConstantBuffer(const ConstantBuffer& in_other)
    {
		HHD_ASSERT( in_other._start_address != NULL );
		HHD_ASSERT(in_other._size != 0);

		_start_address = (byte_t*) Factory::acquireMemoryBlock( in_other._size );
		memset(_start_address, 0x00, in_other.size());
		_size = in_other._size;
		memcpy(_start_address, in_other._start_address, _size);
        _shader_bind_flags = in_other._shader_bind_flags;

        //need to handle HashTable
        _shell = in_other._shell;
    }

    ConstantBuffer& ConstantBuffer::operator=(const ConstantBuffer& in_other)
    {
        if( in_other._start_address )
        {
            if( _start_address )
            {
                Factory::releaseMemoryBlock( _start_address );
            }

            _start_address = (byte_t*) Factory::acquireMemoryBlock( in_other._size );
            memset(_start_address, 0x00, in_other.size());
            _size = in_other._size;

            memcpy(_start_address, in_other._start_address, _size);
        }
        else
        {
            _start_address = NULL;
            _size = 0;
        }

        _shader_bind_flags = in_other._shader_bind_flags;

        //need to handle HashTable
        _shell = in_other._shell;
        return *this;
    }

	void ConstantBuffer::build( GfxShaderBindFlags in_flags )
	{
        //do error checking for byte size multiple of 16.
        if( _size % 16 != 0 )
        {
            error("A ConstantBuffer's size is not a multiple of 16 bytes.");
        }

        //copy in information
        _shader_bind_flags = in_flags;

        //get memory block
        _start_address = (byte_t*) Factory::acquireMemoryBlock( _size );
    }

    void ConstantBuffer::addPrimitive( const String& in_name, size_t in_size_of_primitive )
    {
        _shell.add( in_name, _size );
        _size += in_size_of_primitive;
    }

    void ConstantBuffer::clear()
    {
        if( _start_address )
        {
            Factory::releaseMemoryBlock( _start_address );
            _start_address = NULL;
        }

        _size = 0;

        _shader_bind_flags = SBF_NONE;
        _shell.clear();
    }

    size_t ConstantBuffer::size() const
    {
        return _size;
    }

    GfxShaderBindFlags ConstantBuffer::shaderBindFlags() const
    {
        return _shader_bind_flags;
    }

	void ConstantBuffer::deserializeFromXML( const TiXmlElement* in_element )
	{
		if(String::equals(in_element->Value(), "ConstantBuffer"))
		{
			//read off register and shader bind flags attributes
			GfxShaderBindFlags shader_flags;
			String shader_bind_flags(in_element->Attribute("shader_bind_flags"));

			//one stage
			if(shader_bind_flags.equals("V"))
			{
				shader_flags = SBF_VERTEX_SHADER;
			}
			else if(shader_bind_flags.equals("P"))
			{
				shader_flags = SBF_PIXEL_SHADER;
			}
			//two stages
			else if(shader_bind_flags.equals("VP") )
			{
				shader_flags = (GfxShaderBindFlags)(SBF_VERTEX_SHADER | SBF_PIXEL_SHADER);
			}
			//error conditions
			else
			{
				error("bad shader flags given");
			}

			for(const TiXmlElement* element = in_element->FirstChildElement();
				element != NULL;
				element = element->NextSiblingElement())
			{
				String value(element->Value());
				String name(element->Attribute("name"));

				int32_t array_size;
				int32_t result = element->QueryIntAttribute("arraySize", &array_size);

				if(result == TIXML_NO_ATTRIBUTE)
				{
					array_size = 1;
				}

				// add it to the total
				//save of the displacement as a hash based on string name
				if(value.equals("float"))
				{
					addPrimitive( name, sizeof(float) * array_size );
				}
				else if(value.equals("float2"))
				{
					addPrimitive( name, sizeof(float) * 2  * array_size );
				}
				else if(value.equals("float3"))
				{
					addPrimitive( name, sizeof(float) * 3 * array_size );
				}
				else if(value.equals("float4"))
				{
					addPrimitive( name, sizeof(float) * 4 * array_size );
				}
				else if(value.equals("Matrix4"))
				{
					addPrimitive( name, sizeof(Matrix4) * array_size );
				}
				else if(value.equals("Color"))
				{
					addPrimitive( name, sizeof(Color) * array_size );
				}
				else if(value.equals("UINT"))
				{
					addPrimitive( name, sizeof(uint32_t) * array_size );
				}
			}
			//now we need to construct this ConstantBuffer
			build( shader_flags );

			//iterate children to makeup the object
			TiXmlNode* child_child_node = NULL;
			TiXmlElement* child_child_element = NULL;

			for(const TiXmlElement* element = in_element->FirstChildElement();
				element != NULL;
				element = element->NextSiblingElement())
			{
				String value(element->Value());
				String name(element->Attribute("name"));

				// add it to the total
				//save of the displacement as a hash based on string name
				if(value.equals("float"))
				{
					float value;
					child_child_element->QueryFloatAttribute("value", &value);
					setInternal<float>( name, value );
				}
				else if(value.equals("float2"))
				{
					Vector2 value;
					child_child_element->QueryVector2Attribute("value", &value);
					setInternal<Vector2>( name, value );
				}
				else if(value.equals("float3"))
				{
					Vector3 value;
					child_child_element->QueryVector3Attribute("value", &value);
					setInternal<Vector3>( name, value );
				}
				else if(value.equals("float4"))
				{
					Vector4 value;
					child_child_element->QueryVector4Attribute("value", &value);
					setInternal<Vector4>( name, value );
				}
				else if(value.equals("Matrix4"))
				{
					HHD_ASSERT(!"parse for Matrix4 not written");
				}
				else if(value.equals("Color"))
				{
					float r,g,b,a;
					child_child_element->QueryFloatAttribute("r", &r);
					child_child_element->QueryFloatAttribute("g", &g);
					child_child_element->QueryFloatAttribute("b", &b);
					child_child_element->QueryFloatAttribute("a", &a);

					Color value(r,g,b,a);
					setInternal<Color>( name, value );
				}

			}
		}
		else
		{
			HHD_ASSERT(!"Not handed the xml for a Constant Buffer.");
		}
	}

	void ConstantBuffer::copyFromModifier(const MConstantBufferModifier* source)
	{

		//iterate through all the pieces of data that need to be updated
		for( size_t j = 0; j < source->_data.size(); j++ )
		{
			//check the type to set the internal correctly
			switch (source->_types[j])
			{
			case P_FLOAT:
				setInternal<float>(source->_names[j], *(float*)source->_data[j]);
				break;

			case P_FLOAT2:
				setInternal<Vector2>(source->_names[j], *(Vector2*)source->_data[j]);
				break;

			case P_FLOAT3:
				setInternal<Vector3>(source->_names[j], *(Vector3*)source->_data[j]);
				break;

			case P_FLOAT4:
				setInternal<Vector4>(source->_names[j], *(Vector4*)source->_data[j]);
				break;

			case P_FLOAT4X4:
				setInternal<Matrix4>(source->_names[j], *(Matrix4*)source->_data[j]);
				break;

			case P_UINT:
				setInternal<unsigned int>(source->_names[j], *(unsigned int*)source->_data[j]);
				break;

			case P_INT:
				setInternal<int>(source->_names[j], *(int*)source->_data[j]);
				break;

			case P_COLOR:
				setInternal<Color>(source->_names[j], *(Color*)source->_data[j]);
				break;
			}

		}
	}

}
